'''
Created on 06/04/2009

@author: Edward
'''
from yarra.datastore import dsconstants, dsofactory
from yarra.datastore.dsstub import DSStub
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.logging import yarralogging
import datetime
import httplib
import os


class ResponseTimeoutHandler(BaseEventHandler):
    '''
    classdocs
    '''
    
    __logger = None
    
    def __init__(self):
        self.__logger = yarralogging.get_logger(DSStub().get_application_name())
        
    def do(self, data):
        dso = data
        request_id = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                                 predicate=dsconstants.PREDICATE_REQUEST_ID).get_literal()
        ds = DSStub()
        result = ds.get_outstanding_requests(int(request_id))
        if result:
            (http_request, lock) = result
        else:
            self.__logger.info('Cannot find message entry with request_id ' + str(request_id))
            return
        
        fault_message = 'spear-im-not-available'

        relative_path = "../../../pages/im/imerror.html"
        
        # get the html template
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        html_string = html_template_string.replace('${fault_message}', fault_message)
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)
        event = Event(eventconstants.HTTP_RESPONSE_EVENT_TYPE, new_dso)
        EventManager().add_event(event)